package com.teapos.service;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import jodd.http.HttpRequest;
import jodd.http.HttpResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.teapos.dao.CustomerDao;
import com.teapos.dao.OrderDao;
import com.teapos.dao.QRcodeDao;
import com.teapos.enumtype.OrderStatusEnum;
import com.teapos.enumtype.YNEnum;
import com.teapos.util.BusinessTool;
import com.teapos.util.Maps;
import com.teapos.util.PropUtil;
import com.teapos.util.ThreadLocalUtil;
import com.teapos.util.Tool;

@SuppressWarnings({"rawtypes", "unchecked"})
@Service
public class CoreService {
	
	@Autowired
	private CustomerDao customerDao;
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private QRcodeDao qRcodeDao;

	@Transactional(readOnly=false, propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public String checkAndSaveOrder(HttpServletRequest req) {
		String cardNo = req.getParameter("vip_no");
		String password = req.getParameter("vip_pwd");
		if(StringUtils.isNotBlank(cardNo)) {
			Map account = customerDao.findVipAccount(Maps.newHashMap("cardno", cardNo, "password", password));
			if(account==null) throw new RuntimeException("会员卡密码错误！！");
		}
		
		//System.err.println(Tool.getCookieValue(req, "order"));
		//System.err.println(Tool.getCookieValue(req, "products"));
		//System.err.println(Tool.getCookieValue(req, "saves"));
		//System.err.println(Tool.getCookieValue(req, "customer"));
		
		Map orderMap = JSON.parseObject(Tool.getCookieValue(req, "order"));
		List productList = JSON.parseArray(Tool.getCookieValue(req, "products"));
		List saveList = JSON.parseArray(Tool.getCookieValue(req, "saves"));
		Map customerMap = JSON.parseObject(Tool.getCookieValue(req, "customer"));
		
		List temps = JSON.parseArray(Tool.getCookieValue(req, "temps"));
		System.err.println(temps);
		//System.err.println(orderMap);
		//System.err.println(productList);
		//System.err.println(saveList);
		//System.err.println(customerMap);
		
		Map user = (Map)ThreadLocalUtil.get("user");
		System.err.println(user);
		
		String orderId = BusinessTool.generateId();
		
		String orderNo = BusinessTool.generateOrderNo();
		new Maps(orderMap).put("has_save", saveList.size()==0?0:1).put("customer_id", customerMap.get("id"))
			.put("user_id", user.get("user_id")).put("user_name", user.get("user_name"))
			.put("store_id", user.get("store_id")).put("store_name", user.get("store_name"))
			.put("id", orderId).put("order_no", orderNo);
		orderDao.saveOrder(orderMap);
		Iterator iter = null;
		
		if(!CollectionUtils.isEmpty(temps)) {
			iter = temps.iterator();
			while(iter.hasNext()) {
				Map temp = (Map)iter.next();
				//int unit = Unit4SaveEnum.getEnumByDesc(Tool.toString(temp.get("type_display"))).getCode();
				//temp.put("unit", unit);
				int unit = Tool.toInt(temp.get("unit_type"));
				Map data = Maps.newHashMap(temp.get("commodity_id"), Maps.newHashMap("type", 0
						 , "unit", unit, "customerId", customerMap.get("id"), "count", 1));
				HttpResponse response = HttpRequest
				        .post(PropUtil.getValueByKey("url.temp"))
				        .form("storeId", user.get("store_id"), "data", JSON.toJSONString(data))
				        .send();
				Map result = JSON.parseObject(response.body());
				System.err.println(result);
				String msg = Tool.toString(result.get(temp.get("product_id")));
				if("error".equals(msg)) throw new RuntimeException("生成报警单失败！！");
			}
		}
		
		if(productList.size()>0) {
			iter = productList.iterator();
			while(iter.hasNext()) {
				Map product = (Map)iter.next();
				changeItem(product, orderId);
				product.put("order_no", orderNo);
				
				//绑定客户
				qRcodeDao.bindUserCode(Maps.newHashMap("customer_id", customerMap.get("id")
						, "customer_name", customerMap.get("name"), "code", product.get("qrcode_id")));
				//扣减仓库库存
				//int unit = Unit4SaveEnum.getEnumByDesc(Tool.toString(product.get("type"))).getCode();
				//product.put("unit", unit);
				int unit = Tool.toInt(product.get("unit_type"));
				product.put("unit", product.get("type"));
				Map data = Maps.newHashMap(product.get("product_id"), Maps.newHashMap("type", 0
				 , "unit", unit, "customerId", 0, "count", 1));
				//System.err.println(JSON.toJSONString(data));
				
				HttpResponse response = HttpRequest
				        .post(PropUtil.getValueByKey("url.stock"))
				        .form("storeId", user.get("store_id"), "data", JSON.toJSONString(data))
				        .send();
				System.err.println(response.body());
				Map result = JSON.parseObject(response.body());
				String msg = Tool.toString(result.get(product.get("product_id")));
				if("error".equals(msg)) throw new RuntimeException("扣减库存失败！！");
			}
			orderDao.saveOrderItems(productList);
		}
		
		if(saveList.size()>0) {
			iter = saveList.iterator();
			while(iter.hasNext()) {
				Map save = (Map)iter.next();
				changeItem(save, orderId);
				save.put("order_no", orderNo);
				//增加寄存客库存
				//int unit = save.get("type").equals("散装")?0:1;
				//save.put("unit", unit);
				int unit = Tool.toInt(save.get("unit_type"));
				save.put("unit", save.get("type"));
				Map data = Maps.newHashMap(save.get("product_id"), Maps.newHashMap("type", 0
				 , "unit", unit, "customerId", customerMap.get("id"), "count", -1));
				//System.err.println(JSON.toJSONString(data));
				
				HttpResponse response = HttpRequest
				        .post(PropUtil.getValueByKey("url.stock"))
				        .form("storeId", user.get("store_id"), "data", JSON.toJSONString(data))
				        .send();
				Map result = JSON.parseObject(response.body());
				String msg = Tool.toString(result.get(save.get("product_id")));
				if("error".equals(msg)) throw new RuntimeException("增加库存失败！！");
			}
			System.err.println(productList);
			
			orderDao.saveOrderItems(saveList);
		}
		return orderId;
	}
	
	private void changeItem(Map item, String orderId) {
		Maps.changeKey(item, "code", "qrcode_id");
		Maps.copyValue(item, "name", "product_name");
		Maps.copyValue(item, "price", "org_price");
		Maps.copyValue(item, "price2", "now_price");
		if(item.get("discount").equals("无")) item.put("discount", 1);
		Maps.put(item, "id", BusinessTool.generateId(), "order_id", orderId);
		System.err.println(item);
	}

	public void cancelOrder(String orderId) {
		orderDao.updateOrder(Maps.newHashMap("id", orderId, "order_status", OrderStatusEnum.CANCELD.getCode()));
		Map order = orderDao.findOrderById(orderId);
		List items = orderDao.findItemsByOrderId(orderId);
		Iterator iter = items.iterator();
		//解绑客户和二维码
		while(iter.hasNext()) {
			Map item = (Map)iter.next();
			qRcodeDao.bindUserCode(Maps.newHashMap("code", item.get("qrcode_id"), "customer_id", 0, "customer_name", 0));
			
			//int unit = Tool.toInt(item.get("unit"));
			//int type = unit==0||unit==1?0:1;
			int unit =Tool.toInt(item.get("unit_type"));
			int type = 0;// TODO 暂时写死
			Map data = Maps.newHashMap(item.get("product_id"), Maps.newHashMap("type", type
			 , "unit", unit, "customerId", 0, "count", -1));
			//返还仓库库存
			HttpResponse response = HttpRequest
			        .post(PropUtil.getValueByKey("url.stock"))
			        .form("storeId",order.get("store_id"), "data", JSON.toJSONString(data))
			        .send();
			Map result = JSON.parseObject(response.body());
			String msg = Tool.toString(result.get(item.get("product_id")));
			if("error".equals(msg)) throw new RuntimeException("扣减库存失败！！");
			
			//寄存的商品需要扣减寄存客库存
			int isSave = Tool.toInt(item.get("is_save"));
			if(isSave==YNEnum.YES.getCode()) {
				data = Maps.newHashMap(item.get("product_id"), Maps.newHashMap("type", type
						 , "unit", unit, "customerId", order.get("customer_id"), "count", 1));
				response = HttpRequest
				        .post(PropUtil.getValueByKey("url.stock"))
				        .form("storeId",order.get("store_id"), "data", JSON.toJSONString(data))
				        .send();
				result = JSON.parseObject(response.body());
				msg = Tool.toString(result.get(item.get("product_id")));
				if("error".equals(msg)) throw new RuntimeException("扣减库存失败！！");
			}
		}
		//qRcodeDao.bindUserCode(Maps.);
	}

}
